package cn.ac.iie.di.worker;

import cn.ac.iie.di.global.GlobalParas;
import cn.ac.iie.di.redisutil.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author spf
 */
public class DwdPic implements Runnable {

        public static Logger log = Logger.getLogger(DwdPic.class.getName());
        long et;                              // 时间间隔时间  
        private static Object dirLock = new Object();
        RedisUtil redisUtil;

        private static boolean makeDir(File dir) {
                synchronized (dirLock) {
                        if (dir.exists()) {
                                return true;
                        } else {
                                return dir.mkdirs();
                        }
                }
        }

        @Override
        public void run() {
                while (true) {
                        HashMap map = new HashMap();
                        LinkedList list = new LinkedList();
                        String[] path = null;
                        String[] url = null;
                        try {
                                map = GlobalParas.dwdMsgPool.poll(20, TimeUnit.MILLISECONDS);
                                if (map == null) {
                                        if (GlobalParas.killDownPic) {
                                                break;
                                        }
                                        continue;
                                }
                                Iterator it = map.entrySet().iterator();
                                //则操作一个数组
                                while (it.hasNext()) {
                                        Map.Entry entry = (Map.Entry) it.next();
                                        String colName = (String) entry.getKey();
                                        if (colName.equals(GlobalParas.urlColumnName)) {
                                                list = (LinkedList) map.get(colName);
                                                url = (String[]) list.get(1);
                                        }
                                        if (colName.equals(GlobalParas.pathColumnName)) {
                                                list = (LinkedList) map.get(colName);
                                                path = (String[]) list.get(1);
                                        }
                                }

                                if (url == null || url.length == 0) {
                                        log.debug(" no file in " + GlobalParas.urlColumnName);
                                        continue;
                                }
                                if (path == null || path.length == 0) {
                                        log.debug(" no file in " + GlobalParas.pathColumnName);
                                        continue;
                                }

                                String urlAndAddr = "";

                                log.info(path.length + " wait to dwd");
                                for (int k = 0; k < path.length; k++) {
                                        String trueUrl = "";
                                        if ("".equals(path[k]) || path[k] == null) {
                                                continue;
                                        }
                                        String dwdUrl = url[k];
                                        if ("".equals(dwdUrl) || dwdUrl == null) {
                                                continue;
                                        }
                                        //get true url
                                        String httpMsg = "";
                                        String str = "";
                                        //统计下载一张图片所花费的时间
                                        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
                                        try {
                                                HttpPost httpPost = new HttpPost(GlobalParas.httpUrl);
                                                httpMsg = "{\"cmd\":16,\"url\":\"" + dwdUrl + "\"}";
                                                StringEntity reqEntity = new StringEntity(httpMsg, Charset.forName("UTF-8"));
                                                reqEntity.setContentType("application/json");// 区分不同种类的数据,xml数据
                                                long st = System.currentTimeMillis();
                                                httpPost.setEntity(reqEntity);
                                                CloseableHttpResponse response = httpClient.execute(httpPost);
                                                HttpEntity entity = response.getEntity();
                                                log.info("get true url time is : " + (System.currentTimeMillis() - st));
                                                str = EntityUtils.toString(entity, "utf-8");
                                                log.debug(str);
                                                httpPost.releaseConnection();
                                                JSONObject json = JSONObject.parseObject(str);
                                                String dataString = json.getString("data");
                                                String codeString = json.getString("code");
                                                String errString = json.getString("errorinfo");
                                                if (dataString.equals("")) {
                                                        log.warn("the return jsonStr : " + str);
                                                        log.warn("no file in data");
                                                        log.warn(dwdUrl);
                                                        log.warn("err code is: " + codeString);
                                                        log.warn("err info is: " + errString);
                                                        continue;
                                                }
                                                JSONObject urlJson = JSONObject.parseObject(dataString);
                                                trueUrl = urlJson.getString("download_url");
                                                trueUrl = trueUrl.replace("10.177.138.34:8080", "10.238.3.12:8080");
                                                String tmpUrlAddr = trueUrl + "￥" + path[k] + "￥" +dwdUrl;
                                                log.debug("tmpUrlAddr is : " + tmpUrlAddr);
                                                //将一个消息中的所有图片的url和对应的地址，写入到一个String中
                                                if (urlAndAddr.equals("")) {
                                                        urlAndAddr = tmpUrlAddr;
                                                } else {
                                                        urlAndAddr = urlAndAddr + "$" + tmpUrlAddr;
                                                }
                                                log.debug("urlAndAddr is : " + urlAndAddr);
                                                if (GlobalParas.countQuest.getAndIncrement() >= GlobalParas.questMax) {
                                                        log.warn(GlobalParas.dateInfo + " quest times is : " + GlobalParas.countQuest.get() + " bigger than " + GlobalParas.questMax);
                                                        break;
                                                }
                                        } catch (Exception ex) {
                                                log.error("get url fail ,and the str is " + str + " the httpMsg is " + httpMsg + ex, ex);
                                                if (GlobalParas.countQuest.getAndIncrement() >= GlobalParas.questMax) {
                                                        log.warn(GlobalParas.dateInfo + " quest times is : " + GlobalParas.countQuest.get() + " bigger than " + GlobalParas.questMax);
                                                        break;
                                                }
                                                continue;
                                        }
                                }
                                //如果url都没有获取到的话，应该直接continue
                                if ("".equals(urlAndAddr)) {
                                        continue;
                                }
                                List finalList = new ArrayList();
                                finalList.add(map);
                                finalList.add(urlAndAddr);

                                boolean offer = GlobalParas.urlAndAddrPool.offer(finalList);
                                while (!offer) {
                                        Thread.sleep(500);
                                        offer = GlobalParas.urlAndAddrPool.offer(finalList);
                                }

                                if (GlobalParas.killDownPic) {
                                        break;
                                }

                                if (GlobalParas.countQuest.get() >= GlobalParas.questMax) {
                                        log.warn(GlobalParas.dateInfo + " quest times is : " + GlobalParas.countQuest.get() + " bigger than " + GlobalParas.questMax);
                                        break;
                                }

                        } catch (Exception ex) {
                                log.error(ex, ex);
                        }
                }

                if (!GlobalParas.DwdPicQueue.isEmpty()) {
                        GlobalParas.DwdPicQueue.poll();
                        log.info("GlobalParas.DwdPicQueue size is : " + GlobalParas.DwdPicQueue.size());
                }
                log.info("DownPic exit ");
        }
}
